from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadData
from app.settings.base import jwtToenKey

class JwtTokenError(RuntimeError):
    def __init__(self, errMsg):
        self.errMsg = errMsg

    def data(self, errDetails):
        self.errDetails = errDetails
        return self


ErrJwtTokenCreateFailed = JwtTokenError('创建token失败')
ErrJwtTokenTokenExpires = JwtTokenError('token expires')
ErrJwtTokenVerify = JwtTokenError('token认证失败')


class JwtToken:
    def __init__(self):
        '''
        定义签名密钥，用于校验jwt的有效、合法性
        实例化jwt序列化对象，设置salt和超时时间，默认超时时间3600秒
        '''
        self.key = jwtToenKey
        self.jwtSerializer = Serializer(self.key, expires_in=3600 * 24 * 30)

    def createToken(self, user_info):
        '''创建token'''
        try:
            # userRoleId = user_info['userRoleId']
            # if 'cashier' == userRoleId:
            #     self.jwtSerializer.expires_in = 3600 * 24
            # else:
            #     self.jwtSerializer.expires_in = 2000
            token = self.jwtSerializer.dumps(user_info).decode()
        except Exception as e:
            raise ErrJwtTokenCreateFailed.data(str(e))
        return token

    def verifyToken(self, token):
        '''校验token的函数，校验通过则返回解码信息'''
        try:
            userInfo = self.jwtSerializer.loads(token)
        except SignatureExpired:
            raise ErrJwtTokenTokenExpires
        except BadData:
            raise ErrJwtTokenVerify
        return userInfo
